Grep : How to grep for strings inside binary data
Grep or Global Regular Expression Print is a very useful Unix/Linux command that I've practically used everyday. So, recently a co-worker asked me how to grep
for a piece of string inside binary data files ?
for example, there is a binary file
printf "\x01 text \x00\r\ntext\r\n\x02text text\r\n\x92" > data.bin
What he wanted is to grep for the 'text' string for the data.bin file
To do that, use the cat
command with -v
flag
From the cat
man page:
-v Display non-printing characters so they are visible. Control characters print as ^X' for control-X; the delete character (octal 0177) prints as `^?.
Non-ASCII characters (with the high bit set) are printed as `M-' (for meta) followed by the character for the low 7 bits.
without the -v
flag, the grep result will look something like this
cat data.bin | grep text
Binary file (standard input) matches
therefore, use cat -v
before passing the result to grep
cat -v data.bin | grep text
^A text ^@^M
text^M
^Btext text^M
Hope this short tutorial on greping for strings inside binary data file can be useful to you.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.1k Golang : Generate Interleaved 2 inch by 5 inch barcode
+33.6k Golang : Proper way to set function argument default value
+6.7k Golang : Gargish-English language translator
+7.6k Javascript : How to check a browser's Do Not Track status?
+5k JavaScript/JQuery : Redirect page examples
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+11.4k Golang : Convert(cast) float to int
+12.4k Swift : Convert (cast) Int or int32 value to CGFloat
+10.3k Golang : Get local time and equivalent time in different time zone
+6.7k Golang : Levenshtein distance example
+20.5k Golang : Underscore or snake_case to camel case example